import * as Koa from 'koa';
// import * as jwt from 'koa-jwt'; // API Auth0保证数据和内容，通过token对JSON进行验签，暂时不用
import * as bodyParser from 'koa-bodyparser';
import * as KoaViews from 'koa-views'
import * as helmet from 'koa-helmet';
// import * as cors from '@koa/cors';
import * as winston from 'winston';
import * as dotenv from 'dotenv';
import { createConnection } from 'typeorm';
import 'reflect-metadata';
import * as KoaStatic from 'koa-static'
import * as path from 'path'

import { logger } from './logging';
import { config } from './config';
import { router } from './routes';

// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config({ path: '.env' });

createConnection({
  type: 'sqlite',
  database: config.SQLiteDatabase,
  synchronize: true,
  logging: false,
  entities: [
    'src/entity/**/*.ts'
  ],
}).then(async connection => {

  const app = new Koa();
  app.use(KoaViews(__dirname + '/views', {
    map: {
      html: 'ejs',
    }
  }))

  app.use(helmet());
  app.use(logger(winston));
  app.use(bodyParser());
  app.use(function(ctx, next){
    return next().catch((err) => {
      if (401 == err.status) {
        ctx.status = 401;
        ctx.body = 'Protected resource, use Authorization header to get access\n';
      } else {
        throw err;
      }
    });
  });

  app
    .use(router.routes())
    .use(router.allowedMethods());

  const staticPath = './views/public'
  app.use(KoaStatic(
    path.join(__dirname, staticPath),
  ))
  app.listen(config.port);
  console.log(`Server running on port ${config.port}`);

}).catch(error => console.log('TypeORM connection error: ', error));